<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs' /* 假设已安装dayjs，用于时间格式化 */
import {
  Clock,
  Document,
  Refresh,
  Delete,
  VideoPlay,
  VideoPause,
  RefreshLeft,
  Setting,
  CircleClose, // 新增导入退出图标
} from '@element-plus/icons-vue'

const router = useRouter()

// 用户信息
const user = JSON.parse(localStorage.getItem('user')) || {}
const realName = ref(user.realName || '')
const employeeId = ref(user.employeeId || '')
const userId = user.id

if (!localStorage.getItem('token') || !employeeId.value) {
  ElMessage.error('请先登录')
  router.push('/login')
}

// 计时相关
const operationTypeId = ref(null)
const duration = ref(0)
const isTiming = ref(false)
const isPaused = ref(false)
let timer = null
let startTime = null

const startTiming = () => {
  if (!operationTypeId.value) {
    ElMessage.error('请选择操作类型')
    return
  }
  startTime = new Date()
  isTiming.value = true
  isPaused.value = false
  timer = setInterval(() => {
    if (!isPaused.value) duration.value++
  }, 1000)
}

const stopTiming = async () => {
  clearInterval(timer)
  isTiming.value = false
  const endTime = new Date()
  const calcDuration = Math.floor((endTime - startTime) / 1000)
  try {
    const response = await axios.post(
      // 存储响应以便调试
      '/api/timer-records',
      {
        userId: userId,
        operator: realName.value,
        duration: calcDuration,
        startTime: startTime.toISOString(),
        endTime: endTime.toISOString(),
        operationTypeId: operationTypeId.value,
        status: 'completed',
      }
      // 移除 { headers: ... }，依赖全局拦截器
    )
    ElMessage.success('记录创建成功')
    loadRecords()
    resetTiming()
  } catch (error) {
    console.error('创建记录错误:', error.response?.data) // 调试日志
    ElMessage.error(error.response?.data?.message || '创建记录失败') // 显示后端具体错误
  }
}

const pauseTiming = () => {
  isPaused.value = !isPaused.value
}

const resetTiming = () => {
  clearInterval(timer)
  duration.value = 0
  isTiming.value = false
  isPaused.value = false
  startTime = null
}

// 记录表格
const records = ref([])
const loading = ref(false)

const loadRecords = async () => {
  loading.value = true
  try {
    const response = await axios.get(`/api/timer-records/employee/${employeeId.value}`, {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
    })
    records.value = response.data
    calculateTodayWorkTime()
    updatePaginatedRecords()
  } catch (error) {
    ElMessage.error('获取记录失败')
  }
  loading.value = false
}

const deleteRecord = async (id) => {
  try {
    await axios.delete(`/api/timer-records/${id}`, {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
    })
    ElMessage.success('删除成功')
    loadRecords()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 格式化函数
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const formatDate = (row, column, cellValue) => {
  return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
}

// 计算今日总工作时长
const totalWorkTimeToday = ref(0)

const calculateTodayWorkTime = () => {
  const today = dayjs().format('YYYY-MM-DD')
  totalWorkTimeToday.value = records.value
    .filter((record) => dayjs(record.startTime).format('YYYY-MM-DD') === today)
    .reduce((total, record) => total + record.duration, 0)
}

// 添加分页逻辑
const currentPage = ref(1)
const pageSize = 5
const paginatedRecords = ref([])

const handlePageChange = (page) => {
  currentPage.value = page
  updatePaginatedRecords()
}

const updatePaginatedRecords = () => {
  const start = (currentPage.value - 1) * pageSize
  paginatedRecords.value = records.value.slice(start, start + pageSize)
}

// 新增退出登录函数
const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  ElMessage.success('已退出登录')
  router.push('/login')
}

onMounted(() => {
  loadRecords()
})
</script>

<template>
  <div class="home-wrapper">
    <div class="home-container">
      <el-row :gutter="24" class="main-layout" justify="center">
        <!-- 左侧区域：个人信息和选择 -->
        <el-col :span="8" class="left-panel">
          <el-card class="info-card" shadow="hover">
            <div class="info-header">
              <!-- 移除头像 -->
              <div class="info-text">
                <h2>{{ realName }}</h2>
                <p class="employee-id">工号: {{ employeeId }}</p>
                <p class="welcome-text">今日已工作: {{ formatTime(totalWorkTimeToday) }}</p>
              </div>
              <div class="status-indicator">
                <el-tag type="success" size="large">在线</el-tag>
              </div>
            </div>
            <!-- 添加退出登录按钮 -->
            <div class="logout-section">
              <el-button type="danger" size="small" :icon="CircleClose" @click="logout"
                >退出登录</el-button
              >
            </div>
          </el-card>

          <el-card class="selection-card" shadow="hover">
            <h3 class="section-title">
              <el-icon><Setting /></el-icon>
              工作选择
            </h3>
            <el-form>
              <el-form-item label="操作类型">
                <el-select
                  v-model="operationTypeId"
                  placeholder="请选择工作类型"
                  clearable
                  size="large"
                  class="operation-select"
                >
                  <el-option label="装配作业" :value="1" />
                  <el-option label="焊接作业" :value="2" />
                  <el-option label="喷涂作业" :value="3" />
                  <el-option label="质检检查" :value="4" />
                  <el-option label="包装作业" :value="5" />
                  <el-option label="设备维护" :value="6" />
                  <el-option label="物料搬运" :value="7" />
                  <el-option label="清洁整理" :value="8" />
                </el-select>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 右侧区域：计时操作 -->
        <el-col :span="16" class="right-panel">
          <el-card class="timer-card" shadow="hover">
            <div class="timer-header">
              <h2 class="timer-title">
                <el-icon><Clock /></el-icon>
                工作计时器
              </h2>
              <div class="timer-status" v-if="isTiming">
                <el-tag :type="isPaused ? 'warning' : 'success'" size="large">
                  {{ isPaused ? '已暂停' : '计时中' }}
                </el-tag>
              </div>
            </div>

            <div class="timer-display-main">
              <div class="current-time">{{ formatTime(duration) }}</div>
              <p class="time-label">当前计时</p>
            </div>

            <div class="timer-controls-main">
              <el-button
                type="primary"
                :icon="VideoPlay"
                @click="startTiming"
                v-if="!isTiming"
                size="large"
                class="control-btn main-btn"
                >开始工作</el-button
              >
              <el-button
                type="danger"
                :icon="VideoPause"
                @click="stopTiming"
                v-else
                size="large"
                class="control-btn main-btn"
                >结束工作</el-button
              >
              <el-button
                type="warning"
                :icon="isPaused ? VideoPlay : VideoPause"
                @click="pauseTiming"
                :disabled="!isTiming"
                size="large"
                class="control-btn"
                >{{ isPaused ? '继续' : '暂停' }}</el-button
              >
              <el-button
                type="info"
                :icon="RefreshLeft"
                @click="resetTiming"
                size="large"
                class="control-btn"
                >重置</el-button
              >
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 底部表格区域 -->
      <el-row :gutter="20" class="table-row" justify="center">
        <el-col :span="24">
          <el-card class="records-card" shadow="hover">
            <div class="records-header">
              <h3 class="section-title">
                <el-icon><Document /></el-icon>
                工作记录
              </h3>
              <el-button
                type="primary"
                :icon="Refresh"
                @click="loadRecords"
                :loading="loading"
                size="small"
                >刷新记录</el-button
              >
            </div>

            <el-table
              :data="paginatedRecords"
              v-loading="loading"
              stripe
              height="400"
              class="records-table"
              :row-style="{ height: '60px' }"
              :fit="true"
            >
              <el-table-column prop="id" label="ID" align="center" />
              <el-table-column prop="operationType.name" label="操作类型" show-overflow-tooltip />
              <el-table-column prop="duration" label="用时" align="center">
                <template #default="{ row }">
                  {{ formatTime(row.duration) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="startTime"
                label="开始时间"
                :formatter="formatDate"
                show-overflow-tooltip
              />
              <el-table-column
                prop="endTime"
                label="结束时间"
                :formatter="formatDate"
                show-overflow-tooltip
              />
              <el-table-column label="状态" align="center">
                <template #default="{ row }">
                  <el-tag type="success" size="small">已完成</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="{ row }">
                  <el-popconfirm
                    title="确认删除这条记录吗？"
                    @confirm="deleteRecord(row.id)"
                    confirm-button-text="确认"
                    cancel-button-text="取消"
                  >
                    <template #reference>
                      <el-button type="danger" size="small" :icon="Delete">删除</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
              <template #empty>
                <el-empty description="暂无记录" :image-size="100" />
              </template>
            </el-table>

            <el-pagination
              background
              layout="total, prev, pager, next, jumper"
              :total="records.length"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
              class="pagination"
            />
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped>
.home-wrapper {
  max-width: 1200px; /* 缩小max-width，使内容紧凑，增加留白舒适度 */
  margin: 0 auto;
  padding: 0 20px; /* 增加padding添加舒适留白 */
}

.home-container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  box-sizing: border-box;
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  overflow-y: auto;
  z-index: 1;
}

/* 内容层相对定位，高z-index */
.main-layout,
.table-row {
  position: relative;
  z-index: 2;
}

.left-panel {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.right-panel {
  display: flex;
  flex-direction: column;
}

.table-row {
  margin-top: 24px;
}

/* 信息卡片样式 */
.info-card {
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  backdrop-filter: blur(4px);
  border: 1px solid rgba(255, 255, 255, 0.18);
}

.info-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
}

/* 移除头像相关样式 */
.info-text h2 {
  margin: 0;
  font-size: 24px;
  color: #2c3e50;
  font-weight: 600;
}

.employee-id {
  margin: 8px 0 4px 0;
  color: #7f8c8d;
  font-size: 16px;
  font-weight: 500;
}

.welcome-text {
  margin: 0;
  color: #4caf50;
  font-size: 14px;
  font-weight: 500;
}

.status-indicator {
  margin-left: auto;
}

/* 选择卡片样式 */
.selection-card {
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  backdrop-filter: blur(4px);
  border: 1px solid rgba(255, 255, 255, 0.18);
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #2c3e50;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.operation-select {
  width: 100%;
}

/* 计时卡片样式 */
.timer-card {
  height: 100%;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  backdrop-filter: blur(4px);
  border: 1px solid rgba(255, 255, 255, 0.18);
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.timer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  padding: 0 20px;
}

.timer-title {
  margin: 0;
  font-size: 28px;
  color: #2c3e50;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}

.timer-status {
  margin-left: auto;
}

.timer-display-main {
  text-align: center;
  margin: 40px 0;
}

.current-time {
  font-size: 64px;
  font-weight: bold;
  color: #4caf50;
  margin: 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.time-label {
  margin: 8px 0 0 0;
  color: #7f8c8d;
  font-size: 16px;
}

.timer-controls-main {
  display: flex;
  justify-content: center;
  gap: 16px;
  flex-wrap: wrap;
  padding: 0 20px;
}

.control-btn {
  min-width: 140px;
  border-radius: 12px;
  font-weight: 500;
  padding: 16px 24px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.control-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.main-btn {
  min-width: 160px;
  font-size: 18px;
}

/* 记录卡片样式 */
.records-card {
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  backdrop-filter: blur(4px);
  border: 1px solid rgba(255, 255, 255, 0.18);
}

.records-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

/* 优化表格样式，增加间距 */
.records-table {
  border-radius: 12px;
  margin-bottom: 24px;
  width: 100%;
}

.records-table :deep(.el-table__header) th {
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  font-weight: 600;
}

.records-table :deep(.el-table__row) {
  transition: background-color 0.3s ease;
}

.records-table :deep(.el-table__row:hover) {
  background-color: #f8f9fa !important;
}

/* 添加row-style增加行间距 */
.records-table :deep(.el-table__body tr) {
  height: 60px; /* 增加行高，避免挤压 */
}

.pagination {
  text-align: center;
  padding: 16px 0;
}

:deep(.el-card__body) {
  padding: 24px;
}

/* 动画效果 */
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

.current-time {
  animation: pulse 2s infinite;
}

.control-btn:active {
  transform: scale(0.98);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .home-wrapper {
    max-width: 100%;
    padding: 0 10px;
  }

  .main-layout {
    flex-direction: column;
  }

  .left-panel,
  .right-panel {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .home-wrapper {
    padding: 0 5px;
  }

  .info-header {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }

  .status-indicator {
    margin-left: 0;
    margin-top: 12px;
  }

  .timer-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .current-time {
    font-size: 48px;
  }

  .records-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .timer-controls-main {
    flex-direction: column;
    align-items: center;
  }

  .control-btn {
    width: 100%;
    max-width: 300px;
  }
}

/* 添加退出按钮样式 */
.logout-section {
  margin-top: 16px;
  text-align: right;
}
</style>
